package com.ybw.redis.page.service;

import com.alibaba.fastjson.JSON;
import com.ybw.redis.page.constant.RedisPreConstant;
import com.ybw.redis.page.constant.VisitConstant;
import com.ybw.redis.page.dto.VisitDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

/**
 * @author ybwei
 * @date 2022/3/7 17:42
 **/
@Slf4j
@Service
public class VisitServiceImpl implements VisitService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void visit(VisitDTO visitDTO) {
        log.info("visitDTO:{}", JSON.toJSONString(visitDTO));
        //1、生成key
        String key = new StringBuilder(RedisPreConstant.VISIT_LIMIT).append(":")
                .append(visitDTO.getUserId()).append(":")
                .append(visitDTO.getGoodsId()).append(":")
                .append(LocalDate.now().toString())
                .toString();
        //2、增加访问次数
        Long visitCount = redisTemplate.opsForValue().increment(key);
        redisTemplate.expire(key, 1L, TimeUnit.DAYS);
        log.info("当前访问量限制:{}", visitCount);
        //3、校验
        if (visitCount != null && visitCount > VisitConstant.MAX_VISIT_COUNT.longValue()) {
            log.info("已超过访问量限制:{}", visitCount);
            return;
        }
    }
}
